export default {
    registerAsync (context, { username, password }) {
        return new Promise((resolve) => {
            setTimeout(() => {
                const userData = localStorage.getItem('userData') ? JSON.parse(localStorage.getItem('userData')) : []
                let flag = false
                if (userData.some(item => item.username === username)) {
                    flag = false
                } else {
                    userData.push({ username, password })
                    localStorage.setItem('userData', JSON.stringify(userData))
                    flag = true
                }
                resolve(flag)
            }, 1000)
        })
    },
    loginAsync (context, { username, password }) {
        // console.log('user action:', { username, password })
        return new Promise((resolve) => {
            setTimeout(() => {
                const userData = localStorage.getItem('userData') ? JSON.parse(localStorage.getItem('userData')) : []
                const cartData = localStorage.getItem('cartData') ? JSON.parse(localStorage.getItem('cartData')) : []
                let data = {}
                let code = 0
                let cartList = []
                if (userData.some(item => item.username === username && item.password === password)) {
                    data = {
                        isLogin: true,
                        username,
                        token: 'token' + password
                    }
                    code = 200
                } else {
                    data = {
                        isLogin: false,
                        username: '游客',
                        token: ''
                    }
                    code = 0
                }
                if (cartData.some(item => item.username === data.username)) {
                    cartList = cartData.filter(item => item.username === data.username)[0].cartList
                }
                // context.commit('login', data)
                resolve({ code, data, cartList })
            }, 1000)
        })
    },
    logoutAsync (context) {
        return new Promise((resolve) => {
            setTimeout(() => {
                const cartData = localStorage.getItem('cartData') ? JSON.parse(localStorage.getItem('cartData')) : []

                const data = {
                    isLogin: false,
                    username: '游客',
                    token: ''
                }
                const code = 200
                let cartList = []

                if (cartData.some(item => item.username === data.username)) {
                    cartList = cartData.filter(item => item.username === data.username)[0].cartList
                }

                // context.commit('login', data)
                resolve({ code, data, cartList })
            }, 1000)
        })
    }
}
